local LB_U = require "packages.lb_kill_utility.utility"

local skel = fk.CreateSkill {
  name = "lb_zero__youmeng",
  max_branches_use_time = {
    ["youmeng1"] = {
      [Player.HistoryRound] = 1
    },
    ["youmeng2"] = {
      [Player.HistoryRound] = 1
    },
    ["youmeng3"] = {
      [Player.HistoryRound] = 1
    },
  }
}

Fk:loadTranslationTable {
  ["lb_zero__youmeng"] = "游梦",
  [":lb_zero__youmeng"] = "每轮每项各限一次，每回合第X张牌被使用后（X为你背置牌数且至少为1），你可观看使用者一张牌及以下一项，将观看牌以任意顺序置于牌堆顶：" ..
      "1.你任意张背置牌；" ..
      "2.处于处理区或装备区的此牌；" ..
      "3.其场上一张牌；然后你将一张牌当【五谷丰登】对你与当前回合角色使用并摸一张牌。",

  ["@[skill_choices]lb_zero__youmeng"] = "游梦",

  ["#lb_zero__youmeng_1"] = "你的任意张背置牌",
  ["#lb_zero__youmeng_2"] = "处于处理区或装备区的此牌",
  ["#lb_zero__youmeng_3"] = "其场上的一张牌",

  ["#lb_zero__youmeng_some"] = "游梦",
  ["#lb_zero__youmeng-choose"] = "游梦：你可以观看 %dest 一张牌及以下一项，将观看牌以任意顺序置于牌堆顶",
  ["#lb_zero__youmeng-choose-from"] = "游梦：请选择 %src 一张牌观看",
  ["#lb_zero__youmeng-choose-back"] = "游梦：请选择任意张背置牌",
  ["#lb_zero__youmeng-choose-area"] = "游梦：请选择 %src 场上一张牌",
  ["#lb_zero__youmeng-use"] = "游梦：请将一张牌当【五谷丰登】对你与%src使用",
  ["#lb_zero__youmeng-use_some"] = "游梦：请将一张牌当【五谷丰登】对你使用",
  ["#lb_zero__youmeng-sort"] = "游梦：以任意顺序置于牌堆顶（左侧牌在上）",

  ["$lb_zero__youmeng1"] = "让我们的灵魂共鸣！",
  ["$lb_zero__youmeng2"] = "我的歌声与你同在。",
  ["$lb_zero__youmeng3"] = "这首歌，献给世界！",
}


skel:addEffect(fk.CardUseFinished, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) then
      local room = player.room
      local current_event = room.logic:getCurrentEvent()
      local turn = current_event:findParent(GameEvent.Turn)
      if turn == nil then return end
      local turn_events = table.slice(room.logic.all_game_events, turn.id)
      local events = {}
      for _, event_ in ipairs(turn_events) do
        if event_.event == GameEvent.UseCard then
          table.insert(events, event_)
        end
      end
      local times = math.max(1, #LB_U.getBackCards(player))
      if events[times] and events[times].data == data then
        local from = data.from
        if from and from:isAlive() and not from:isNude() then
          local choices = {}
          if skel:withinBranchTimesLimit(player, "youmeng1", Player.HistoryRound) and #LB_U.getBackCards(player) > 0 then
            if from ~= player or #player:getCardIds("he") > 1 then
              table.insert(choices, "#lb_zero__youmeng_1")
            end
          end
          if skel:withinBranchTimesLimit(player, "youmeng2", Player.HistoryRound)
              and #table.filter(Card:getIdList(data.card), function(id)
                local area = room:getCardArea(id)
                return area == Card.Processing or area == Card.PlayerEquip
              end) > 0 then
            table.insert(choices, "#lb_zero__youmeng_2")
          end
          if skel:withinBranchTimesLimit(player, "youmeng3", Player.HistoryRound) and #from:getCardIds("ej") > 0 then
            if #from:getCardIds("e") > 1 then
              table.insert(choices, "#lb_zero__youmeng_3")
            else
              local num = 0
              for _, flag in ipairs({ "h", "e", "j" }) do
                if #from:getCardIds(flag) > 0 then
                  num = num + 1
                end
              end
              if (num > 1) then
                table.insert(choices, "#lb_zero__youmeng_3")
              end
            end
          end
          if #choices == 0 then return end
          event:setCostData(self, { choices = choices })
          return true
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local choices = event:getCostData(self).choices
    if #choices == 0 then return end
    local room = player.room
    local all_choices = { "#lb_zero__youmeng_1", "#lb_zero__youmeng_2", "#lb_zero__youmeng_3", "Cancel" }
    table.insert(choices, "Cancel")
    local choice = room:askToChoice(player, {
      choices = choices,
      all_choices = all_choices,
      skill_name = skel.name,
      prompt = "#lb_zero__youmeng-choose::" .. data.from.id,
    })
    if choice ~= "Cancel" then
      event:setCostData(self, { choice = choice })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local branch = tonumber(event:getCostData(self).choice:sub(-1))
    player:addSkillBranchUseHistory(skel.name, "youmeng" .. branch)
    local ids = {}
    local one = room:askToChooseCard(player, {
      target = data.from,
      flag = "he",
      skill_name = skel.name,
      prompt = "#lb_zero__youmeng-choose-from:" .. data.from.id
    })
    if one then
      table.insert(ids, one)
      room:viewCards(player, {
        cards = ids,
        skill_name = skel.name,
      })
    end
    if branch == 1 then
      table.insertTableIfNeed(ids, room:askToCards(player, {
        min_num = 1,
        max_num = math.huge,
        skill_name = skel.name,
        cancelable = false,
        pattern = tostring(Exppattern { id = LB_U.getBackCards(player) }),
        prompt = "#lb_zero__youmeng-choose-back",
      }))
    elseif branch == 2 then
      table.insertTableIfNeed(ids, Card:getIdList(data.card))
    elseif branch == 3 then
      local two = room:askToChooseCard(player, {
        target = data.from,
        flag = "ej",
        skill_name = skel.name,
        prompt = "#lb_zero__youmeng-choose-area:" .. data.from.id
      })
      if two then
        table.insertIfNeed(ids, two)
      end
    end
    if #ids > 0 then
      if #ids > 1 then
        ids = room:askToGuanxing(player, {
          cards = ids,
          area_names = { "Top", "toObtain" },
          top_limit = { #ids, #ids },
          bottom_limit = { 0, 0 }, --为0不显示第二行
          skill_name = skel.name,
          prompt = "#lb_zero__youmeng-sort",
          skip = true,
        }).top
        ids = table.reverse(ids)
      end
      local move_list = {}
      for _, id in ipairs(ids) do
        local owner = room:getCardOwner(id)
        if owner then
          owner = room:getPlayerById(owner.id)
        end
        local move = { ---@type CardsMoveInfo
          ids = { id },
          from = owner,
          toArea = Card.DrawPile,
          moveReason = fk.ReasonPut,
          skillName = skel.name,
          proposer = player,
          moveVisible = owner and false or true, -- 处理区的牌移动必须可见，否则会有卡手牌的情况
          drawPilePosition = 1,
        }
        table.insert(move_list, move)
      end
      --room:moveCardTo(table.reverse(put), Card.DrawPile, nil, fk.ReasonPut, skel.name, nil, false)
      room:moveCards(table.unpack(move_list))
      if player:isAlive() then
        local tos = { player }
        local current = room:getCurrent()
        if current:isAlive() then
          table.insertIfNeed(tos, current)
        end
        room:askToUseVirtualCard(player, {
          name = "amazing_grace",
          skill_name = skel.name,
          cancelable = false,
          prompt = #tos == 1 and "#lb_zero__youmeng-use_some" or ("#lb_zero__youmeng-use:" .. current.id),
          card_filter = { n = 1 },
          extra_data = { fix_targets = table.map(tos, Util.IdMapper) }
        })
        if player:isAlive() then
          player:drawCards(1, skel.name)
        end
      end
    end
  end,
})

skel:addAcquireEffect(function(self, player, is_start)
  local list = {
    ["name"] = skel.name,
    ["scope"] = Player.HistoryRound,
    ["choices"] = { { "youmeng1" }, { "youmeng2" }, { "youmeng3" } }
  }
  player.room:setPlayerMark(player, "@[skill_choices]lb_zero__youmeng", list)
end)

skel:addLoseEffect(function(self, player, is_death)
  player.room:setPlayerMark(player, "@[skill_choices]lb_zero__youmeng", 0)
end)

return skel
